package com.easyfun.healthmagicbox.inputviews;

import java.sql.SQLException;
import java.util.Map;
import java.util.Map.Entry;

import android.content.Context;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.easyfun.healthmagicbox.R;
import com.iflytek.speech.ErrorCode;
import com.iflytek.speech.ISpeechModule;
import com.iflytek.speech.InitListener;
import com.iflytek.speech.RecognizerListener;
import com.iflytek.speech.RecognizerResult;
import com.iflytek.speech.SpeechRecognizer;
import com.iflytek.speech.util.JsonParser;
import com.j256.ormlite.dao.Dao;
import com.easyfun.healthmagicbox.base.BaseActivity;
import com.easyfun.healthmagicbox.base.DatabaseAccess;
import com.easyfun.healthmagicbox.base.DatabaseAccessImplementation;
import com.easyfun.healthmagicbox.comm.HealthInputDataUploadTask;
import com.easyfun.healthmagicbox.comm.HealthThreadPool;
import com.easyfun.healthmagicbox.ormlite.DatabaseHelper;
import com.easyfun.healthmagicbox.ormlite.HealthInputTypeEnum;
import com.easyfun.healthmagicbox.pojo.ConstantData;
import com.easyfun.healthmagicbox.pojo.HealthInputData;
import com.easyfun.healthmagicbox.sync.BasicCommCallback;
import com.easyfun.healthmagicbox.util.VoiceTextToValueData;

public class VoiceInputActivity extends BaseActivity implements DatabaseAccess {
	private final static String LOG_TAG = VoiceInputActivity.class.getName();
	private SpeechRecognizer mIat;
	private Toast mToast;
	
	private VoiceTextToValueData vvv = new VoiceTextToValueData();
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.inputvoice);
		
		addbackButton(this);
		//personal ID
		if (!checkPersonId()) return;
		
		Button butStart = (Button) findViewById(R.id.btn_voice_start);
		butStart.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v) {
				mIat.startListening(mRecognizerListener);
				
			}
		
		});
		
		Button butStop = (Button) findViewById(R.id.btn_voice_stop);
		butStop.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v) {
				EditText editor = ((EditText)findViewById(R.id.iat_text));
				String text = editor.getText().toString() ; //
				mIat.stopListening(mRecognizerListener);
				processVoiceResult(text);
			}
		
		});
		setupView();
		// 初始化识别对象
		mIat = new SpeechRecognizer(this, mInitListener);
		mToast = Toast.makeText(this, "", Toast.LENGTH_LONG);
	}

	/**
	 * 初期化监听器。
	 */
	private InitListener mInitListener = new InitListener() {

		@Override
		public void onInit(ISpeechModule module, int code) {
			Log.d(LOG_TAG, "SpeechRecognizer init() code = " + code);
			if (code == ErrorCode.SUCCESS) {
				findViewById(R.id.btn_voice_start).setEnabled(true);
			}
		}
	};

	private void setupView() {
		findViewById(R.id.btn_voice_start).setEnabled(false);
		findViewById(R.id.btn_voice_save).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				EditText editor = ((EditText)findViewById(R.id.iat_text));
				processVoiceResult(editor.getText().toString());
				
			}
		});

	}

	private void showTip(final String str) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				mToast.setText(str);
				mToast.show();
			}
		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 退出时释放连接
		mIat.cancel(mRecognizerListener);
		mIat.destory();
	}


	/**
	 * match database result
	 * @param iattext
	 */
	private void processVoiceResult(String iattext) {
		Map<HealthInputTypeEnum, String> saveToDB = vvv.convertTo(iattext);
		
		Dao<HealthInputData, Integer> inputDataDao;
		// get our dao
		try {
			inputDataDao = getHelper(this).getInputDataDao();
			Log.i(LOG_TAG, "get last input data.");
		} catch (SQLException e) {
			e.printStackTrace();
			return;
		}
		
		for(Entry<HealthInputTypeEnum, String> entry : saveToDB.entrySet()) {
			HealthInputTypeEnum key = entry.getKey();
			String value = entry.getValue();
			HealthInputData hid = new HealthInputData(m_personid,key.toInteger(),
					value,
					System.currentTimeMillis());
			try {
				inputDataDao.create(hid);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		HealthInputDataUploadTask task = new HealthInputDataUploadTask(
				this, 
				m_personid, 
				new BasicCommCallback());
		HealthThreadPool.getInstance().execute(task);
		
	}
	private RecognizerListener mRecognizerListener = new RecognizerListener.Stub() {

		@Override
		public void onVolumeChanged(int v) throws RemoteException {
			showTip("onVolumeChanged：" + v);
		}

		@Override
		public void onResult(final RecognizerResult result, final boolean isLast)
				throws RemoteException {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					if (null != result) {
						// 显示
						Log.d(LOG_TAG,
								"recognizer result：" + result.getResultString());
						String iattext = JsonParser.parseIatResult(result
								.getResultString());
						EditText editor = ((EditText)findViewById(R.id.iat_text));
						String text = editor.getText().toString() + iattext; //
						editor.setText(text);
						//if (isLast) processVoiceResult(iattext);
					} else {
						Log.d(LOG_TAG, "recognizer result : null");
						showTip("无识别结果");
					}
				}

			});

		}
		
		@Override
		public void onBeginOfSpeech() throws RemoteException {
			showTip("onBeginOfSpeech");

		}

		@Override
		public void onEndOfSpeech() throws RemoteException {
			showTip("onEndOfSpeech");

		}

		@Override
		public void onError(int errorCode) throws RemoteException {
			showTip("onError Code："	+ errorCode);

		}
	};
	@Override
	public DatabaseHelper getHelper(Context context) {
		return DatabaseAccessImplementation.getInstance().getHelper(this);
	}

}
